package com.ruantong.dingtalk.ding.openapi;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiDepartmentListRequest;
import com.dingtalk.api.response.OapiDepartmentListResponse;
import com.ruantong.dingtalk.ding.openapi.token.DingTokenStore;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @description:钉钉部门相关api
 * @author: jh.chen
 * @time: 2020/11/14 10:50
 */
@Component
@Slf4j
public class DepartmentApi {

    @Autowired
    private DingTokenStore dingTokenStore;

    /**
     * 获取部门信息
     *
     * @param: [fetchChild, deptId] fetchChild：是否递归获取子部门,deptId：部门id，根部门为1
     * @return: java.util.List<com.dingtalk.api.response.OapiDepartmentListResponse.Department>
     */
    public List<OapiDepartmentListResponse.Department> deptList(boolean fetchChild, String deptId) {
        List<OapiDepartmentListResponse.Department> list = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
            OapiDepartmentListRequest req = new OapiDepartmentListRequest();
            req.setFetchChild(fetchChild);
            req.setId(deptId);
            req.setHttpMethod("GET");
            OapiDepartmentListResponse rsp = client.execute(req, dingTokenStore.getToken());
            list = rsp.getDepartment();
            log.info("DepartmentList from DingTalk:{}", JSON.toJSONString(rsp));
        } catch (ApiException e) {
            log.error(e.getErrCode(), e.getErrMsg());
        }
        return list;
    }
}
